package main

import (
	"fmt"
	"io/ioutil"
	"math/rand"
	"net/http"
	"strconv"
	"strings"
	"time"
)

//var beginId int = 1500
//var count int = 100
var trueCount int = 0
var invokeCount = 0
var count= 1
var batch int = 1
var totalSendLoopCount int = 2000


func main() {

	// startTime := time.Now().Unix()
	totalCount := batch*count*totalSendLoopCount
	/*   chs := make ([] chan int, count)
	//    for i := 0; i < count ; i++{
	//        chs[i] = make (chan int)
	//       go sendHttp(chs[i],i)
	//       sendHttp(chs[i],i)
	//        time.Sleep(1 * time.Second)
	    }*/


	msg := make(chan int, 0)
	tmp := 0
	for i := 0; i < totalSendLoopCount ; i++{
		for j := 0; j < count ; j++{

			timeBegin := time.Now().UnixNano()
			for k := 0; k < batch ; k++{
				//chs[tmp] = make (chan int)
				//go sendHttp(chs[tmp],k)
				go sendHttp(msg,tmp)
				tmp = tmp +1
			}

			sleepTime := int64(1000000000/count)- (time.Now().UnixNano()- timeBegin)  //单位纳秒
			fmt.Println("I am going to sleep %d", sleepTime)
			time.Sleep( time.Duration(sleepTime) * time.Nanosecond ) //休眠 sleepTime 纳秒


			//time.Sleep( 500 * time.Millisecond)
		}
	}

	//没有以下一段话，在执行的时候，不等待sendHttp执行完，main函数就执行完毕了，会导致sendHttp里面的函数不能执行完，也可估算程序运行时间加个sleep
	/*  for _, ch := range(chs){
	        <-ch
	    }
	*/

	for i := 0; i < totalCount; i++ {
		<-msg
	}
	fmt.Println("successTimes is ", trueCount)
	fmt.Println("sendTotalTimes is ", count)


}



func sendHttp(ch chan int,i int ){

	url := "http://192.168.9.65:8081/chaincode/invoke"

	var b string = "a" + strconv.Itoa(rand.Int())
	a := fmt.Sprintf("{\n\t\t\t \"channel\":\"mychannel\", \n\t\t\t\"ccName\":\"mycc\", \n\t\t\t\"fcn\":\"CreateAsset\", \n\t         \"args\":[\"%s\",\"blue\",\"b1\",\"1\"],\n\t           \"orderer\":\"orderer-0-certbaas2gm\",\n\t         \"peers\":[\"peer-0-certbaas2gm\"]\n\n}\n", b)
	payload := strings.NewReader(a)

	req, _ := http.NewRequest("POST", url, payload)

	req.Header.Add("Content-Type", "application/json")
	req.Header.Add("token", "f63d1a26-6ed3-11e8-9f0b-ff73e95c8ddb")

	res, _ := http.DefaultClient.Do(req)

	defer res.Body.Close()
	body, _ := ioutil.ReadAll(res.Body)

	fmt.Println(res)
	fmt.Println(string(body))

	ch<- i
}